-- Copyright 2012 Martti Merilaid, Nicolas BARBOTIN
-- This file is part of LuaTanks.
-- 
-- LuaTanks is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
-- 
-- LuaTanks is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-- GNU General Public License for more details.
-- 
-- You should have received a copy of the GNU General Public License
-- along with LuaTanks.  If not, see <http://www.gnu.org/licenses/>.

TOOL.Category   = "LuaTanks"
TOOL.Name       = "Contest Starter"

if SERVER then
	CreateConVar("luatanks_maxtime", 60)
end

if CLIENT then
	language.Add("tool.luatanks.name", "LuaTanks Contest Starter")
	language.Add("tool.luatanks.desc", "Starts a LuaTanks contest")
	language.Add("tool.luatanks.0", "Primary: Start the contest")


	function TOOL.BuildCPanel(CPanel)
		CPanel:AddControl("Header", { Text = "#tool.luatanks.name", Description = "#tool.luatanks.desc" })

		local timeForCoding = vgui.Create("DNumSlider")
		timeForCoding:SetMin(5)
		timeForCoding:SetMax(1440)
		timeForCoding:SetConVar("luatanks_maxtime")
		timeForCoding:SetValue(60)
		timeForCoding:SetText("Maximum time for coding tanks")
		timeForCoding:SizeToContents()
		CPanel:AddItem(timeForCoding)

		local playerList = vgui.Create("DListBox")
		playerList:SetMultiple(true)
		playerList:Clear()

		for k, v in pairs(player.GetAll()) do
			if v:IsValid() and v:SteamID() != LocalPlayer():SteamID() then
				playerList:AddItem(v:GetName())
			end
		end

		playerList:SetSize(100, 350)
		CPanel:AddItem(playerList)

		local refreshBtn = vgui.Create("DButton")
		refreshBtn:SetText("Refresh playerlist")
		refreshBtn.DoClick = function()
			playerList:Clear()

			for k, v in pairs(player.GetAll()) do
				if v:IsValid() and v:SteamID() != LocalPlayer():SteamID() then
					playerList:AddItem(v:GetName())
				end
			end
		end

		refreshBtn:SetSize(100, 30)
		CPanel:AddItem(refreshBtn)
	end
end

function TOOL:LeftClick(trace)
	if CLIENT then return true end

	if !LTanks.CanCreateContest(self:GetOwner()) then
		self:GetOwner():ChatPrint("[LuaTanks] Access refused by server.")
		return false
	end

	local allPlayer = {} -- /!\ Temporary
	for k, v in pairs(player.GetAll()) do
		if v:SteamID() != self:GetOwner():SteamID() then
			table.insert(allPlayer, v)
		end
	end

	local cID = LTanks.CreateContest(self:GetOwner(), allPlayer, GetConVar("luatanks_maxtime"):GetInt())
	if cID < 0 then
		self:GetOwner():ChatPrint("[LuaTanks] Error when trying to create a contest (" .. tostring(cID) .. ")")
		return false
	end

	return true
end
